/*!
 * \class Logger
 *
 * \brief 日志管理类
 *
 * \author Bryceyam
 * \date ʮһ�� 2025
 */
#pragma once
#include "LogRecord/globle.h"
#include <list>
#include <queue>
#include <memory>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>

class LogRecorder;
typedef std::shared_ptr<LogRecorder> LogRecorderPtr;

class LOGRECORDER_API Logger
{
public:
	static Logger& getInstance();

	~Logger();

	/*
	*@brief      日志启动
	*/
	bool start();

	/*
	*@brief      日志接口
	*@param[in]  level日志等级 log日志内容 file日治所在文件 line日志所在行数
	*/
	void doWrite(LogLevel level, const std::string& log, const std::string& file, int line);

	void addLogRecorder(LogRecorderPtr logrecorder);

	void delLogRecorder(LogRecorderPtr logrecorder);

	void stop();
private:
	struct LogInfo
	{
		LogLevel level;//日志级别
		std::string log; //日志内容
		std::string file; //日志所在文件
		int line;//日志所在行数

		LogInfo(LogLevel level, const std::string& log, const std::string& file, int line)
		{
			this->level = level;
			this->log = log;
			this->file = file;
			this->line = line;
		}
	};

	std::list<LogRecorderPtr> mLogRecordList;// 注册的日志器列表
	std::queue<LogInfo> mTaskQueue; // 日志任务队列
	std::mutex mQueueMutex;         // 保护队列的互斥锁
	std::condition_variable mCv;    // 条件变量，用于线程间通知
	std::thread mWorkerThread;      // 唯一的后台工作线程
	bool mShutdownFlag = false;     // 优雅关闭标志

	Logger();

	/*
	*@brief      线程入口函数
	*/
	void run();
};

#define LOGGER Logger::getInstance()
#define FORMAT(level, format, ...) do { \
        const size_t buffer_size = 512; \
        char buffer[buffer_size]; \
        snprintf(buffer, buffer_size, format, ##__VA_ARGS__); \
        Logger::getInstance().doWrite(LogLevel::DEBUG, std::string(buffer), __FILE__, __LINE__); \
    } while(0)
#define DEBUGLOGGER(format, ...)  FORMAT(LogLevel::DEBUG, format, ##__VA_ARGS__)
#define INFOLOGGER(format, ...) FORMAT(LogLevel::INFO, format, ##__VA_ARGS__)
#define WARNLOGGER(format, ...) FORMAT(LogLevel::WARN, format, ##__VA_ARGS__)
#define ERRORLOGGER(format, ...) FORMAT(LogLevel::ERROR, format, ##__VA_ARGS__)